<?php
namespace ticket\libs;

use Yii;
/*
工具类
*/
class Tools
{

	/*返回函数（前端接受使用）*/
    public static function showRes($code = 0, $msg = '提交成功', $data = '', $url = '')
    {
        $res = array(
            "code" => $code,
            'msg' => $msg,
        );

        if(!empty($data)){
            $res['data'] = $data;
        }
        
        if(!empty($url)){
            $res['url'] = $url;
        }
        return json_encode($res, JSON_UNESCAPED_UNICODE);
    }

    /*返回函数（前端接受使用）*/
    public static function returnRes($code = 0, $data = '')
    {
        $res = array(
            "code" => $code
        );

        if(!empty($data)){
            $res['data'] = $data;
        }
        
        return (object)$res;
    }

    /*
    根据尺寸，返回对应的图片
    如果没有对应的尺寸图，就返回原始图，如果原始图
    $Imgurl     需要转换的图片路径
    $size       需要转换的图片尺寸
    */
    public static function getImgBySize($Imgurl, $size='thumb'){
        $size = $size.'_img';
        $sizes = Yii::$app->params['imgSize'];//所有配置尺寸
        $suffix = explode('.', $Imgurl)[1];
        $tmp = explode('!!', $Imgurl);
        if(count($tmp)>1){//有裁剪尺寸
            $tmp2 = explode('_', $tmp[1]);
            $len = $tmp2[0];//此图片有多少尺寸
            $i = count($sizes);
            foreach(array_reverse($sizes) as $k => $v){
                if($k == $size){
                    if($i <= $len){
                        $newImgurl = $tmp[0].'!!'.$len.'_'.$sizes[$size].'x'.$sizes[$size].'.'.$suffix;
                    }
                }
                $i--;
            }
            $Imgurl = $tmp[0].'.'.$suffix;
        };
        return isset($newImgurl)?$newImgurl:$Imgurl;
    }

    /*产生6位随机字符串*/
    public static function generateStr($length=6) { 
        // 密码字符集，可任意添加你需要的字符 
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; 
        $randStr = ''; 
            for($i=0; $i<$length; $i++) { 
                // 这里提供两种字符获取方式 
                // 第一种是使用 substr 截取$chars中的任意一位字符； 
                // $randStr .= substr($chars, mt_rand(0, strlen($chars) – 1), 1); 
                // 第二种是取字符数组 $chars 的任意元素 
                $randStr .= $chars[mt_rand(0, strlen($chars)-1)];
            };
        return $randStr; 
    }

    public static function setUrl($params)
    {
        return "/". $params .".html";
    }

    /*** CryptoJS 解密
     * @param $data
     */
    public static function Decryption($data)
    {
        $key = Yii::$app->params['CryptoJS']['key'];
        $iv = Yii::$app->params['CryptoJS']['iv'];
        $data = base64_decode($data);
        $res = openssl_decrypt($data,"AES-128-CBC",$key,0,$iv);
        return $res;

    }

    /*** 加密
     * @param $data
     * @return string
     */
    public static function Encrypt($data)
    {
        $key = Yii::$app->params['CryptoJS']['key'];
        $iv = Yii::$app->params['CryptoJS']['iv'];
        $res =  openssl_encrypt($data, "AES-128-CBC", $key,0, $iv);
        return base64_encode($res);
    }


    //统计目录下所有文件的容量
    public static function dirSize ($dir)
    {
        $dh = opendir($dir);             //打开目录，返回一个目录流
        $size = 0;      //初始大小为0 
        while(false !== ($file = @readdir($dh))){     //循环读取目录下的文件
            if($file != '.' and $file != '..'){
                $path = $dir.'/'.$file;     //设置目录，用于含有子目录的情况
                // echo $path."<br>";
                if(is_dir($path)){
                    $size += self::dirSize($path);  //递归调用，计算目录大小
                }elseif(is_file($path)){
                    $size += filesize($path);   //计算文件大小
                }
            } 
        }   
        closedir($dh);             //关闭目录流
        return $size;               //返回大小
    }


    /*统计目录下共有多少个文件*/
    public static function dirFiles($dir)
    {
        $num = 0;//造一个变量，让他默认值为0;
        $arr = glob($dir);//把该路径下所有的文件存到一个数组里面;
        foreach ($arr as $v)//把数组$arr赋给$v;
        {
            if(is_file($v)){//先用个if判断一下这个文件夹下的文件是不是文件，有可能是文件夹;
                $num ++;//如果是文件，数量加一;
            }else{
                $num += self::dirFiles($v . "/*");//如果是文件夹，那么再调用函数本身获取此文件夹下文件的数量，这种方法称为递归;
            }
        }
        return $num;//当这个方法走完后，返回一个值$sl,这个值就是该路径下所有的文件数量;
    }


    /*
    文件大小 单位转换
    $filesize   文件大小
    */
    public static function convertFileUnit($filesize)
    {
        if($filesize >= 1073741824) {
            $filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
        } else if($filesize >= 1048576) {
            $filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
        } else if($filesize >= 1024) {
            $filesize = round($filesize / 1024 * 100) / 100 . ' KB';
        } else {
            $filesize = $filesize . ' Byte';
        }
        return $filesize;
    }


    /**
     * 生成短信签名
     * @param array $data
     * @param string $server_secret
     */
    public static function checkSign(array $data, $server_secret){

        foreach($data as $key => $val){
            if($val == ''){ unset($data[$key]); }
        }
        $data['server_secret'] = $server_secret;
        ksort($data);
        $key_str = urldecode(http_build_query($data));
        $key_str = str_replace('&', '', $key_str);
        $key = strtolower(md5($key_str));
        $code = mt_rand(10000, 99999);

        $data['sign'] = $key;
        return $data;
    }


    /***返回当前的毫秒时间戳
     * @return float
     */
    public static function get_msectime() {
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;

    }
    /*
    产生唯一字符串
    $length        长度
    */
    public static function createStr($length = 30)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

    /*
      产生唯一字符串
      $length        长度
      */
    public static function createSn()
    {
        $characters = '0123456789';
        $randomString = date("YmdHis");
        for ($i = 0; $i < 9; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

    /*xml转JSON*/
    public static function FromXml($xml)
    {
        if (!$xml) {
            return false;
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);

        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }


    /*数组转XML*/
    public static function arrayToXml($data)
    {
        if (!is_array($data) || count($data) <= 0) {
            return false;
        }
        $xml = "<xml>";
        foreach ($data as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }


    /*数组转XML*/
    public static function arrayToXmls($data)
    {
        if (!is_array($data) || count($data) <= 0) {
            return false;
        }
        $xml = "<PWBRequest>";
        foreach ($data as $key => $val) {
            if (is_array($val)){
                $xml .= "<".$key.">";
                foreach ($val as $k => $v){
                    if (is_array($v)){
                        $xml .= "<".$k.">";
                        foreach ($v as $m => $n){
                            $xml .= "<" . $m . ">" . $n . "</" . $m . ">";
                        }
                        $xml .= "</".$k.">";
                    }else{
                        $xml .= "<" . $k . ">" . $v . "</" . $k . ">";
                    }

                }
                $xml .= "</".$key.">";
            }else{
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            }

        }
        $xml .= "</PWBRequest>";
        return $xml;
    }
    /*** 生成订单号
     * @return string
     */
    public static function createOrder($num = 24)
    {
        $characters = date("YmdHis").'0123456789';
        $refund_no = '';
        for ($i = 0; $i < $num; $i++) {
            $refund_no .= $characters[rand(0, strlen($characters) - 1)];
        }
        return 'TK'.$refund_no;
    }


    /*** 去除html标签,
     * @param $str
     * @return string
     */
    public static function cutstrHtml($str)
    {
        $str = strip_tags($str);
        $str = htmlspecialchars_decode($str);
        $str = str_replace("\t", "", $str);
        $str = str_replace("\r\n", "", $str);
        $str = str_replace("\r", "", $str);
        $str = str_replace("\n", "", $str);
        $str = str_replace(" ", "", $str);

        return trim($str);
    }


    public static function file_exists_S3($url)
    {
        $state = @file_get_contents($url,1,null,0,1);//获取网络资源的字符内容
        if($state){
            $date = '../../backend/web/uploads/headimgurl/';
            $filename = $date . time(). '.png';
            if(!file_exists($date)){//创建今天日期的文件夹
                mkdir($date, 0777, true);
                chmod($date, 0777);
            }
            ob_start();//打开输出
            readfile($url);//输出图片文件
            $img = ob_get_contents();//得到浏览器输出
            ob_end_clean();//清除输出并关闭
            $size = strlen($img);//得到图片大小
            $fp2 = @fopen($filename, "a");
            fwrite($fp2, $img);//向当前目录写入图片文件，并重新命名
            fclose($fp2);
            return SITE_URL.$filename;
        }
        else{
            return 0;
        }
    }

    /*
        计算签名
        $param      参数
        $sign       返回值
        */
    public static function computeSign($paraMap,$key, $urlEncode = false)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if (null != $v && "null" != $v && $k != 'sign') {
                if ($urlEncode) {
                    $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        $sign = strtoupper(md5(base64_encode($reqPar . "&key=" . $key)));
        return $sign;
    }


    /*
产生6位随机字符串
$format  all全部 ， num 全部为数字
*/
    public static function generateRandomStr($length = 6, $format = 'all')
    {
        // 密码字符集，可任意添加你需要的字符
        if($format == 'num'){
            $chars = '0123456789';
        }else{
            $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        }
        $randStr = '';
        for($i=0; $i<$length; $i++) {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // $randStr .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
            // 第二种是取字符数组 $chars 的任意元素
            $randStr .= $chars[mt_rand(0, strlen($chars)-1)];
        };
        return $randStr;
    }



    /**
     * 判断是否为合法的身份证号码
     * @param $mobile
     * @return int
     */
    public static function isCreditNo($vStr)
    {
        $vCity = array(
            '11','12','13','14','15','21','22',
            '23','31','32','33','34','35','36',
            '37','41','42','43','44','45','46',
            '50','51','52','53','54','61','62',
            '63','64','65','71','81','82','91'
        );
        if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) return false;
        if (!in_array(substr($vStr, 0, 2), $vCity)) return false;
        $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
        $vLength = strlen($vStr);
        if ($vLength == 18) {
            $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
        } else {
            $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
        }
        if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) return false;
        if ($vLength == 18) {
            $vSum = 0;
            for ($i = 17 ; $i >= 0 ; $i--) {
                $vSubStr = substr($vStr, 17 - $i, 1);
                $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
            }
            if($vSum % 11 != 1) return false;
        }
        return true;
    }


}